<?php

namespace App\Models;

use App\Exceptions\CustomException;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Cashflow extends BaseModel
{
    use HasFactory;
    // 收入
    const TYPE_IN = 10;
    // 支出
    const TYPE_OUT = 20;

    protected $guarded = [];

    public static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            self::cashbookCheck($model->user_id, $model->cashbook_id);
        });
    }

    public static function cashbookCheck($user_id, $cashbook_id)
    {
        $exists = DB::table('user_cashbooks')
            ->where('user_id', $user_id)
            ->where('cashbook_id', $cashbook_id)
            ->exists();

        if (!$exists) {
            throw new CustomException('成员不属于当前账本');
        }
    }

    public function category()
    {
        return $this->hasOne(Category::class, 'id', 'category_id');
    }

    public function user()
    {
        return $this->hasOne(Member::class, 'id', 'user_id');
    }
}
